package com.ktg.mes.pro.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.dv.domain.DvMachineryType;
import com.ktg.mes.md.domain.MdProductBom;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.mapper.ProWaringMapper;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.pro.service.IProWaringService;
import com.ktg.mes.wm.domain.WmStockWillOut;
import com.ktg.mes.wm.service.IWmStockWillOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.pro.mapper.ProWorkorderMapper;
import com.ktg.mes.pro.service.IProWorkorderService;

/**
 * 生产工单Service业务层处理
 *
 * @author yinjinlu
 * @date 2022-05-09
 */
@Service
public class ProWorkorderServiceImpl extends ServiceImpl<ProWorkorderMapper, ProWorkorder> implements IProWorkorderService
{
    @Autowired
    private ProWorkorderMapper proWorkorderMapper;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IWmStockWillOutService wmStockWillOutService;

    /**
     * 查询生产工单
     *
     * @param workorderId 生产工单主键
     * @return 生产工单
     */
    @Override
    public ProWorkorder selectProWorkorderByWorkorderId(Long workorderId)
    {
        return proWorkorderMapper.selectProWorkorderByWorkorderId(workorderId);
    }

    /**
     * 查询生产工单列表
     *
     * @param proWorkorder 生产工单
     * @return 生产工单
     */
    @Override
    public List<ProWorkorder> selectProWorkorderList(ProWorkorder proWorkorder)
    {
        return proWorkorderMapper.selectProWorkorderList(proWorkorder);
    }

    @Override
    public String checkWorkorderCodeUnique(ProWorkorder proWorkorder) {
        ProWorkorder workorder = proWorkorderMapper.checkWorkorderCodeUnique(proWorkorder);
        Long workorderId = proWorkorder.getWorkorderId() == null? -1L: proWorkorder.getWorkorderId();
        if(StringUtils.isNotNull(workorder) && workorder.getWorkorderId().longValue() != workorderId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public List<ProWorkorder> selectSerialNumberList()
    {
        return proWorkorderMapper.selectSerialNumberList();
    }


    /**
     * 新增生产工单
     *
     * @param proWorkorder 生产工单
     * @return 结果
     */
    @Override
    public int insertProWorkorder(ProWorkorder proWorkorder)
    {
        if(proWorkorder.getParentId()!= null){
            ProWorkorder parent = proWorkorderMapper.selectProWorkorderByWorkorderId(proWorkorder.getParentId());
            if(StringUtils.isNotNull(parent)){
                proWorkorder.setAncestors(parent.getAncestors()+","+parent.getParentId());
            }
        }

        //防止重复插入
        ProWorkorder sss = proWorkorder;
        sss.setProductId(proWorkorder.getProductId());
        sss.setBatchCode(proWorkorder.getBatchCode());
        sss.setBucketCode(proWorkorder.getBucketCode());
        QueryWrapper queryWrapper = new QueryWrapper<>(sss);
        List list =  getBaseMapper().selectList(queryWrapper);
        if (list != null && list.size() > 0){
            return -1;
        }

        proWorkorder.setCreateTime(DateUtils.getNowDate());
        int a = proWorkorderMapper.insertProWorkorder(proWorkorder);
        return a;
    }

    /**
     * 修改生产工单
     *
     * @param proWorkorder 生产工单
     * @return 结果
     */
    @Override
    public int updateProWorkorder(ProWorkorder proWorkorder)
    {
        //修改批次总桶数
        ProWorkorder old = getById(proWorkorder.getWorkorderId());
        boolean isChangeBatchCode = false;
        if (!old.getBatchCode().equals(proWorkorder.getBatchCode())){
            isChangeBatchCode = true;
        }

        proWorkorder.setUpdateTime(DateUtils.getNowDate());

        int a = proWorkorderMapper.updateProWorkorder(proWorkorder);
        if (isChangeBatchCode){
        }
        return a;
    }




    /**
     * 批量删除生产工单
     *
     * @param workorderIds 需要删除的生产工单主键
     * @return 结果
     */
    @Override
    public int deleteProWorkorderByWorkorderIds(Long[] workorderIds)
    {
        if (workorderIds.length == 1){
            return proWorkorderMapper.deleteProWorkorderByWorkorderId(workorderIds[0]);
        }

        for (int i = 0; i < workorderIds.length; i++) {
            proWorkorderMapper.deleteProWorkorderByWorkorderId(workorderIds[i]);
        }
        return 1;
    }

    /**
     * 删除生产工单信息
     *
     * @param workorderId 生产工单主键
     * @return 结果
     */
    @Override
    public int deleteProWorkorderByWorkorderId(Long workorderId)
    {
        ProWorkorder workorder = selectProWorkorderByWorkorderId(workorderId);
        if(!OrderStatus.scheduleWait.toName().equals(workorder.getStatus())){
            return -1;
        }

        //删除预出库信息
        QueryWrapper queryWrapper = new QueryWrapper<WmStockWillOut>();
        queryWrapper.eq("stock_type","pro_workorder");
        queryWrapper.eq("stock_id",workorderId);
        wmStockWillOutService.remove(queryWrapper);

        int a = proWorkorderMapper.deleteProWorkorderByWorkorderId(workorderId);
        return a;
    }

    @Override
    public List<ProWorkorder> selectProWorkorderTableList(ProWorkorder proWorkorder) {
        String str = proWorkorder.getProductName();
        proWorkorder.setProductName(null);
        QueryWrapper<ProWorkorder> queryWrapper = new QueryWrapper<>(proWorkorder);
        queryWrapper.like(str != null, "product_name", str);
        queryWrapper.orderByDesc("create_time");
        List<ProWorkorder> list = list(queryWrapper);
        return list;
    }

    /**
     * 修改生产工单状态
     * @param proWorkorder
     */
    @Override
    public int updateWorkorderState(ProWorkorder proWorkorder) {
        return proWorkorderMapper.updateWorkorderState(proWorkorder);
    }

    // 查询产品粘度
    @Override
    public ProWorkorder selectProWorkorderViscosity(Long workorderId) {
        return proWorkorderMapper.selectProWorkorderViscosity(workorderId);
    }

    @Override
    public List<ProWorkorder> TreeResul() {

        return proWorkorderMapper.TreeResul();
    }


    /**
     * 修改排产之后，变更工单xinx
     * @param task
     */
    public boolean setStatusAfterTaskChange(ProTask task){
        //获取所有排产的订单数量
        ProWorkorder proWorkorder = getById(task.getWorkorderId());

        if ((proWorkorder.getBatchCode() == null && task.getBatchNo() != null) || !proWorkorder.getBatchCode().equals(task.getBatchNo())){
            proWorkorder.setBatchCode(task.getBatchNo());
        }
        if (task.getTagDate() != null){
            proWorkorder.setTagDate(task.getTagDate());
        }
        if (task.getRequestDate() != null){
            proWorkorder.setRequestDate(task.getRequestDate());
        }
        if (task.getBucketCode() != null){
            proWorkorder.setBucketCode(task.getBucketCode());
        }
        if (task.getQuantity() != null){
            proWorkorder.setQuantity(task.getQuantity());
        }

        //统计排产数量
        ProTask proTask1 = new ProTask();
        proTask1.setWorkorderId(task.getWorkorderId());
        QueryWrapper<ProTask> taskQueryWrapper = new QueryWrapper<>(proTask1);
        taskQueryWrapper.orderByDesc("create_time");
        taskQueryWrapper.last("limit 1");
        ProTask proTask = proTaskService.getOne(taskQueryWrapper);
        // 根据 `workorder_id`, `task_status` 作唯一判断
        if (proTask != null){
            if (!StringUtils.isEmpty(proTask.getTaskStatus())){
                //跟新生产订单状态
                proWorkorder.setStatus(proTask.getTaskStatus());
            }else if ("0".equals(proTask.getStatus())){
                proWorkorder.setStatus("已排产");
            }else {
                proWorkorder.setStatus("生产中");
            }
            if (proTask.getQuantity() != null){
                proWorkorder.setQuantity(proTask.getQuantity());
            }
            if (proTask.getRequestDate() != null){
                proWorkorder.setRequestDate(proTask.getRequestDate());
            }
            if (proTask.getTag() != null){
                proWorkorder.setTag(proTask.getTag());
            }
            proWorkorder.setUpdateTime(new Date());
            if (proTask.getQuantityNotIn() != null){
                proWorkorder.setQuantityChanged(proTask.getQuantityNotIn());
            }else {
                proWorkorder.setQuantityChanged(proTask.getQuantity());
            }
            return updateById(proWorkorder);
        }else {
            //跟新生产订单状态
            proWorkorder.setQuantityChanged(proWorkorder.getQuantity());
            proWorkorder.setStatus(OrderStatus.scheduleWait.toName());
            proWorkorder.setUpdateTime(new Date());
          return  updateById(proWorkorder);
        }
    }

    /**
     * 更新排产任务对应的生产工单
     */
    public void updateStatusFromTaskId(List<Long> taskIds){
        getBaseMapper().updateStatusFromTaskId(taskIds);
    };

}
